package chen.web.controller.forum;

import java.util.ArrayList;
import java.util.Set;

import javax.validation.ConstraintViolation;


public class JSONResponse {
	// 成功、失败标志
	private boolean success = true;
	// 错误信息
	private ArrayList<JSONError> errors = null;
	// 成功时返回的对象
	private Object returnObject = null;

	public boolean isSuccess() {
		if(errors != null && errors.size() > 0){
			return false;
		}
		return success;
	}

	public void setSuccess(boolean success) {
		this.success = success;
	}

	public ArrayList<JSONError> getErrors() {
		return errors;
	}

	public void setErrors(ArrayList<JSONError> errors) {
		this.errors = errors;
	}

	public void addError(JSONError error) {
		if (this.errors == null) {
			this.errors = new ArrayList<JSONError>();
		}
		this.errors.add(error);
	}

	public Object getReturnObject() {
		return returnObject;
	}

	public void setReturnObject(Object returnObject) {
		this.returnObject = returnObject;
	}
	
	public static JSONResponse successed() {
		JSONResponse ret = new JSONResponse();
		ret.setSuccess(true);
		return ret;
	}
	
	public static JSONResponse successed(Object obj) {
		JSONResponse ret = new JSONResponse();
		ret.setSuccess(true);
		ret.setReturnObject(obj);
		return ret;
	}
	
	public static JSONResponse errorMessage(String message){
		JSONResponse ret = new JSONResponse();
		ret.setSuccess(false);
		ret.addError(JSONError.create(null, message));
		return ret;
	}

	public static JSONResponse invalid(Set failureSet) {
		Set<ConstraintViolation<?>> failures = (Set<ConstraintViolation<?>>) failureSet;
		JSONResponse response = new JSONResponse();
		response.setSuccess(false);
		for (ConstraintViolation<?> failure : failures) {
			response.addError(JSONError.create(failure.getPropertyPath()
					.toString(), failure.getMessage()));
		}
		return response;
	}
	
	public static JSONResponse error(JSONError error){
		JSONResponse response = new JSONResponse();
		response.setSuccess(false);
		response.addError(error);
		return response;
	}
}
